package com.dingup.provider.controller.sys;

import com.dingup.api.Util.JwtTokenUtil;
import com.dingup.api.Util.RedisUtils;
import com.dingup.api.base.HttpResContent;
import com.dingup.api.model.sys.SysDept;
import com.dingup.provider.service.sys.LoadUserPermissionService;
import com.dingup.provider.service.sys.SysDeptService;
import com.suyeer.basic.util.BHttpResUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

import static com.dingup.api.base.BaseUtil.saveErrorMsgAndData;
import static com.dingup.api.base.BaseUtil.saveSuccessMsgAndData;

/**
 * Created by wancheng on 2018/7/27.
 */

@RestController()
@RequestMapping("/dept")
public class SysDeptController {

    private final Long ROOT_DEPTID = 0L;

    @Autowired
    SysDeptService sysDeptService;
    @Autowired
    LoadUserPermissionService loadUserPermissionService;

    @RequestMapping(value = "/all.do",method = RequestMethod.POST)
    public void listAllUser(HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<List<SysDept>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取部门信息");
        try {
            String userAccount = JwtTokenUtil.getUserAccountFromRequset(request);
            loadUserPermissionService.loadUserDataPermission(userAccount);
            List<Long> deptIds = RedisUtils.getInstance().getDataPermissionDept(userAccount);
            List<SysDept> list = sysDeptService.getMyDepts(deptIds);
            saveSuccessMsgAndData(hrc, list);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_depts_by_user.do",method = RequestMethod.POST)
    public void getByUser(HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<List<SysDept>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取当前对象可看的部门信息");
        try {
            List<Long> myDepts = RedisUtils.getInstance().getDataPermissionDept(request);

            List<SysDept> all = sysDeptService.get(ROOT_DEPTID);
            saveSuccessMsgAndData(hrc, all);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }
}
